package com.cheesmo.nzb.client;

import java.util.concurrent.Semaphore;

public final class ConnectionPool
{
	private NNTPConnection[] connections = null;
	private Semaphore sem = null;
	private int connCount;

	public ConnectionPool(ClientConfig cfg) {
		connCount = cfg.getMaxConnections();
		this.connections = new NNTPConnection[connCount];

		for (int i = 0; i < connCount; i++) {
			this.connections[i] = new NNTPConnection(cfg);
		}
		this.sem = new Semaphore(connCount);

		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			public void run() {
				for (int i = 0; i < connCount; i++)
					ConnectionPool.this.connections[i].tryDisconnect();
			}
		});
	}

	public NNTPConnection getConnection()
	{
		try {
			this.sem.acquire();
			for (int i = 0; i < this.connections.length; i++) {
				synchronized (this.connections[i]) {
					if (!this.connections[i].isInUse()) {
						this.connections[i].setInUse(true);
						return this.connections[i];
					}
				}
			}
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public void releaseConnection(NNTPConnection connection) {
		connection.setInUse(false);
		this.sem.release();
	}
}
